package com.gem.taskplan.service;

import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;

import com.gem.taskplan.activity.MessageActivity;
import com.gem.taskplan.activity.R;
import com.gem.taskplan.activity.SetActivity;
import com.gem.taskplan.activity.TabHostActivity;
import com.gem.taskplan.activity.TaskActivity;
import com.gem.taskplan.activity.WorkNewsActivity;
import com.gem.taskplan.activity.WorkTableActivity;
import com.gem.taskplan.http.AsyncHttpClient;
import com.gem.taskplan.http.AsyncHttpResponseHandler;
import com.gem.taskplan.http.RequestParams;
import com.gem.taskplan.util.HttpUtil;
import com.gem.taskplan.util.PropertiesUtil;

import android.R.array;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

/**
 * 
 * 短信推送服务类，在后台长期运行，每个一段时间就向服务器发送一次请求
 * @author jerry
 * 
 */
public class ReceiveMessageService extends Service {

	private String curUser;
	private MyThread myThread;
	private NotificationManager manager;
	private Notification notification;
	private PendingIntent pi;
	private AsyncHttpClient client;
	private boolean flag = true;
	private String url = "/PushMessageServlet";

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		url = "/PushMessageServlet";
		url = PropertiesUtil.getServerURL(this)+url;
		curUser = getSharedPreferences("taskPlanShare", Activity.MODE_PRIVATE).getString("lastUser", "");
		System.out.println("service------oncreate()");
		this.client = new AsyncHttpClient();
		this.myThread = new MyThread();
		this.myThread.start();
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		this.flag = false;
		super.onDestroy();
	}

	private void notification(String sendTime,String content, String type, String state,String sendUser) {
		// 获取系统的通知管理器
		manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		notification = new Notification(R.drawable.logo, sendUser+type,
				System.currentTimeMillis());
		notification.defaults = Notification.DEFAULT_ALL; // 使用默认设置，比如铃声、震动、闪灯
		notification.flags = Notification.FLAG_AUTO_CANCEL; // 但用户点击消息后，消息自动在通知栏自动消失
		notification.flags |= Notification.FLAG_NO_CLEAR;// 点击通知栏的删除，消息不会依然不会被删除

		//		column = {"message_id","message_time","message_receive_user",
		//		"message_send_user","message_content","message_type","message_state" };


		Intent intent=null;
		if(type.equals("分配给您一个任务")){
			intent = new Intent(this,TabHostActivity.class);
		}else if(type.equals("加您为好友")){
			intent = new Intent(this,MessageActivity.class);
			intent.putExtra("action", "2");
		}else if(type.equals("拒绝您的好友邀请")){
			intent = new Intent(this,MessageActivity.class);
			intent.putExtra("action", "3");
		}else {
			intent = new Intent(this,TabHostActivity.class);
			intent.putExtra("action", "4");
		}
		intent.putExtra("message_content", content);
		intent.putExtra("message_type", type);
		intent.putExtra("message_time", sendTime);
		intent.putExtra("message_state", state);
		intent.putExtra("message_send_user", sendUser);

		pi = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);

		notification.setLatestEventInfo(getApplicationContext(), sendUser
				+ "发来消息", content, pi);

		// 将消息推送到状态栏
		manager.notify(0, notification);

	}

	private class MyThread extends Thread {
		@Override
		public void run() {
			while (flag) {
				System.out.println("发送请求");
				try {
					// 每个10秒向服务器发送一次请求
					Thread.sleep(10000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

				// 采用post方式向服务器发送请求
				RequestParams params = new RequestParams();
				params.put("curUser", curUser);
				params.put("action", "queryMessage");
				//验证时否联网
				if(!CheckedNetWork.checkedConnection(ReceiveMessageService.this)){
					return;
				}
				client.post(url, params, new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							byte[] responseBody) {
						System.out.println("请求成功！！！！！！");
						try {
							JSONArray result = new JSONArray(new String(
									responseBody, "utf-8"));
							System.out.println(result.toString());
							//							column = {"message_id","message_time","message_receive_user",
							//									"message_send_user","message_content","message_type","message_state" };
							for(int i = 0;i<result.length();i++){
								JSONObject object = result.getJSONObject(i);
								String message_time = object.getString("message_time");
								String sendUser = object.getString("message_send_user");
								String message_type = object.getString("message_type");
								String message_content = object.getString("message_content");
								String message_state = object.getString("message_state");
								notification(message_time,message_content, message_type, message_state,sendUser);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}  
					@Override  
					public void onFailure(int statusCode, Header[] headers,
							byte[] responseBody, Throwable error) {
						Toast.makeText(getApplicationContext(), "数据请求失败", 0)
						.show();
					}
				});
				/*client.get(url, params,new AsyncHttpResponseHandler() {
					@Override
					public void onSuccess(int statusCode, Header[] headers,
							byte[] responseBody) {
						System.out.println("请求成功！！！！！！");
						try {
							JSONArray result = new JSONArray(new String(
									responseBody, "utf-8"));
							System.out.println(result.toString());
							//							column = {"message_id","message_time","message_receive_user",
							//									"message_send_user","message_content","message_type","message_state" };
							for(int i = 0;i<result.length();i++){
								JSONObject object = result.getJSONObject(i);
								String message_time = object.getString("message_time");
								String sendUser = object.getString("message_send_user");
								String message_type = object.getString("message_type");
								String message_content = object.getString("message_content");
								String message_state = object.getString("message_state");
								if(message_type.equals("加您为好友")){
									notification(message_time,message_content, message_type, message_state,sendUser);
								}
//								JSONArray array = object.getJSONArray("message"+(i+1));
//								String sendUser = array.get
							}


						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] responseBody, Throwable error) {
						Toast.makeText(getApplicationContext(), "数据请求失败", 0)
						.show();
					}
				});
				 */
			}
		}
	}

}
